package com.wellsoft.mobileoa.utils.view;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.os.AsyncTask;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.wellsoft.mobileoa.R;
import com.wellsoft.mobileoa.utils.BaseAction;
import com.wellsoft.mobileoa.utils.BaseActivity;
import com.wellsoft.mobileoa.utils.BaseView;
import com.wellsoft.mobileoa.utils.BaseWidget;
import com.wellsoft.mobileoa.utils.SystemConfig;
import com.wellsoft.mobileoa.wsmodel.WSOA_Action;
import com.wellsoft.mobileoa.wsmodel.WSOA_Page;
import com.wellsoft.mobileoa.wsmodel.WSOA_PageListItem;
import com.wellsoft.mobileoa.wsmodel.WSOA_PostField;
import com.wmobile.utils.ServiceResponse;

public class DataView extends BaseView {
	public ListView dataLv;
	public DataViewAdapter dataAdp;
	public List<Integer> selectedIndex;
	public List<BaseWidget> widgetList;

	public DataView(BaseActivity baseActivity, WSOA_Page page, String url) {
		super(baseActivity);
		this.baseActivity = baseActivity;
		this.page = page;
		this.url = url;

		selectedIndex = new ArrayList<Integer>();
		widgetList = new ArrayList<BaseWidget>();

		isNewPageLoading = false;
	}

	@Override
	public ViewGroup DrawSelf() {
		if (page.getPageListSet().getListItems() == null) {
			page.getPageListSet().setListItems(
					new ArrayList<WSOA_PageListItem>());
		}
		dataAdp = new DataViewAdapter(page.getPageListSet().getListItems(),
				baseActivity);

		selfView = (ViewGroup) LayoutInflater.from(baseActivity).inflate(
				R.layout.dataview, null);
		dataLv = (ListView) selfView.findViewById(R.id.dataview_datalv);

		initTitleBar(selfView);

		dataLv.setOnItemClickListener(listViewOnItemClickListener);
		dataLv.setAdapter(dataAdp);
		if (page.getPageFields() != null && page.getPageFields().size() > 0) {
			for (int i = 0; i < page.getPageFields().size(); i++) {
				BaseWidget baseWidget = BaseWidget.createWidgetFactory(page
						.getPageFields().get(i), DataView.this);
				if (baseWidget != null) {
					widgetList.add(baseWidget);
				}
			}
		}

		initToolBar(selfView);

		return selfView;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			backOnClickListener.onClick(null);
		}

		return super.onKeyDown(keyCode, event);
	}

	OnItemClickListener listViewOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			synchronized (DataView.this.isExecuting) {
				if (isExecuting) {
					return;
				}
				isExecuting = true;

				WSOA_PageListItem listItem = page.getPageListSet()
						.getListItems().get(arg2);
				new AsyncTask<WSOA_PageListItem, Integer, ServiceResponse>() {
					AlertDialog alertDialog;

					protected ServiceResponse doInBackground(
							WSOA_PageListItem... params) {
						WSOA_PageListItem listItem = params[0];
						return BaseAction.executeActions(
								listItem.getActionID(), listItem.getAction(),
								DataView.this, true);
					}

					@Override
					protected void onPreExecute() {
						alertDialog = baseActivity.showWaitingDialog();
					}

					@Override
					protected void onPostExecute(ServiceResponse response) {
						alertDialog.dismiss();
						isExecuting = false;
						if (!response.getExeFlag()) {
							baseActivity.showMessage(response.getMessage());
							return;
						}
						if (!SystemConfig.stringIsNullOrEmpty(response
								.getMessage())
								&& response.getMessage().equals("同步成功")) {
							baseActivity.showMessage(response.getMessage());
							return;
						}
					}

				}.execute(listItem);
//				try {
//					Thread.currentThread().sleep(50);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//				AlertDialog alertDialog = baseActivity.showWaitingDialog();
//				WSOA_PageListItem listItem = page.getPageListSet()
//						.getListItems().get(arg2);
//				ServiceResponse response = BaseAction.executeActions(
//						listItem.getActionID(), listItem.getAction(),
//						DataView.this);
//				alertDialog.dismiss();
//				isExecuting = false;
//				if (!response.getExeFlag()) {
//					baseActivity.showMessage(response.getMessage());
//					return;
//				}
			}
		}

	};

	@Override
	public List<WSOA_PostField> getValue() {
		List<WSOA_PostField> postFields = new ArrayList<WSOA_PostField>();
		WSOA_PostField postField = new WSOA_PostField();
		postField.setFieldValues(dataAdp.getCheckedValues());

		postFields.add(postField);

		for (BaseWidget widget : widgetList) {
			WSOA_PostField widgetPostField = widget.getValue();
			if (widgetPostField != null) {
				postFields.add(widgetPostField);
			}
		}
		return postFields;
	}

	@Override
	public void selectAllItem() {
		dataAdp.selectAll();
	}

	@Override
	public void addNextPage(WSOA_Page newPage) {
		List<WSOA_PageListItem> listItems = page.getPageListSet()
				.getListItems();
		listItems.addAll(newPage.getPageListSet().getListItems());
		page.getPageListSet().setListItems(listItems);
		page.setPageListInfo(newPage.getPageListInfo());
		page.setPageTitle(newPage.getPageTitle());
		initTitleBar(selfView);
		dataAdp.notifyDataSetChanged();
	}

	@Override
	public ServiceResponse checkValid() {
		if (dataAdp.selectedIndex.size() > 0) {
			for (int i = 0; i < widgetList.size(); i++) {
				ServiceResponse response = widgetList.get(i).checkValid();
				if (!response.getExeFlag()) {
					return response;
				}
			}
			return new ServiceResponse(true);
		} else {
			return new ServiceResponse(false, "请选择一行记录！");
		}
	}

	public BaseWidget getWidgetById(String widgetId) {
		for (int i = 0; i < widgetList.size(); i++) {
			if (widgetList.get(i).field.getFieldName() != null
					&& widgetList.get(i).field.getFieldName().equals(widgetId)) {
				return widgetList.get(i);
			}
		}
		return null;
	}
}
